package com.horizon.cloud.base.filter;

import com.horizon.cloud.common.constants.SessionConstants;
import com.horizon.cloud.common.context.SessionHolder;
import com.horizon.cloud.standard.redis.RedisRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.session.Session;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SessionIdFilter extends OncePerRequestFilter {
    /**
     *  RedisSession DAO用来存sessionId-redissession的
     */
    private RedisOperationsSessionRepository sessionRepository;

    /**
     * Redis DAO,用来存userid-sessionid的
     */
    RedisRepository redisRepository;

    public SessionIdFilter(RedisRepository redisRepository,
                           RedisOperationsSessionRepository sessionRepository) {
        this.sessionRepository = sessionRepository;
        this.redisRepository = redisRepository;
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return super.shouldNotFilter(request);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
// 从请求头中，获取用户id
        String userIdentifier = httpServletRequest.getHeader(SessionConstants.USER_IDENTIFIER);
        //存入ThreadLocal中，表示本次请求线程携带的userid
        SessionHolder.setUserIdentifer(userIdentifier);
        /**
         * 在redis 中，根据用户 id获取缓存的 session id
         */
        String sid = redisRepository.getSessionId(userIdentifier);
        if (StringUtils.isNotEmpty(sid))
        {
            /**
             * 判断 分布式 session 是否存在
             */
            Session session = sessionRepository.findById(sid);
            if (null != session)
            {
                SessionHolder.setSid(sid);
            }
        }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
